package cn.qdu.controller;

import cn.qdu.model.User;
import cn.qdu.service.UserService;
import cn.qdu.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/UserLoginServlet") // 添加Servlet注解
public class UserLoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        // 确保密码经过 MD5 加密
        String encryptedPassword = MD5Util.encrypt(password);
        System.out.println("输入的密码（加密后）: " + encryptedPassword); // 调试日志

        User user = userService.login(account, encryptedPassword); // 传递加密后的密码

        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", user);
            session.setAttribute("userId", user.getUserId());  // 新增，专门为点赞功能
            response.sendRedirect(request.getContextPath() + "/home");
        } else {
            System.out.println("登录失败，请检查账号或密码"); // 调试日志
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("/views/auth/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/views/auth/login.jsp").forward(request, response);
    }
}